<script setup>
	import {
		ref,
		reactive,
		watchEffect,
		provide,
		inject,
		onMounted,
		computed,
		getCurrentInstance,
	} from 'vue'
	import { FreeRS } from '../assets/markdown/FreeRS新手指引.js'
	const { proxy } = getCurrentInstance()
	const preview = ref()

	const state = reactive({
		titles: [],
	})

	onMounted(() => {
		//获取到目录元素
		console.log('[ proxy ]', proxy.$refs.preview.$el)
		const anchors =
			proxy.$refs.preview.$el.querySelectorAll('h1,h2,h3,h4,h5,h6')
		const titles = Array.from(anchors).filter(
			(title) => !!title.innerText.trim()
		)
		if (!titles.length) {
			state.titles = []
			return
		}
		const hTags = Array.from(
			new Set(titles.map((title) => title.tagName))
		).sort()
		state.titles = titles.map((el) => ({
			title: el.innerText,
			lineIndex: el.getAttribute('data-v-md-line'),
			indent: hTags.indexOf(el.tagName),
		}))
	})
	const handleAnchorClick = (anchor) => {
		const { lineIndex } = anchor
		const heading = preview.value.$el.querySelector(
			`[data-v-md-line="${lineIndex}"]`
		)
		if (heading) {
			// preview.value.scrollToTarget({
			// 	target: heading,
			// 	scrollContainer: window,
			// 	top: 60,
			// })  无效
			heading.scrollIntoView({
				behavior: 'smooth', // 平滑过渡
				block: 'start', // 上边框与视窗顶部平齐。默认值
			})
		}
	}
</script>
<template>
	<div class="doc-div">
		<div class="doc-left">
			<div
				v-for="anchor in state.titles"
				:style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }"
				@click="handleAnchorClick(anchor)"
			>
				<a style="cursor: pointer">{{ anchor.title }}</a>
			</div>
		</div>
		<div class="doc-right">
			<div class="doc-body">
				<v-md-preview ref="preview" :text="FreeRS"></v-md-preview>
			</div>
		</div>
	</div>
</template>
<style scoped lang="less">
	.doc-div {
		width: 100vw;
		height: 100vh;
		display: flex;

		.doc-left {
			width: 12%;
			min-width: 150px;
			height: 100%;
			padding: 2% 2%;
			> div:hover {
				color: #3eaf7c;
			}
			> div:nth-child(1) {
				color: #3eaf7c;
			}
		}
		.doc-right {
			overflow: auto;
			width: 88%;
			height: 100%;
			padding: 3.5%;
			.doc-body {
				// 通过deep可在css预处理比如less中不去掉scoped修改第三方样式
				:deep(.vuepress-markdown-body h1) {
					font-weight: 700;
				}
			}
		}
	}
</style>
